package com.frost.book.interceptor;

import com.frost.book.constant.Constant;
import com.frost.book.model.Result;
import com.frost.book.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        log.info("目标方法执行前执行：LoginInterceptor.preHandle...");
        // true-放行 false-拦截
        // 验证用户是否登录
        HttpSession session = request.getSession();
        UserInfo userInfo = (UserInfo) session.getAttribute(Constant.USER_SESSION_KEY);
        if (userInfo == null || userInfo.getId() < 1) {
            // http 状态码
            response.setStatus(401);
            return false;
        }
        return true;
    }

//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        log.info("目标方法执行后执行：LoginInterceptor.postHandle...");
//    }
//
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        log.info("视图渲染后执行：LoginInterceptor.afterCompletion...");
//    }
}
